package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: OrderServiceImpl
 * @Author 贾金博
 * @Package com.sky.service.impl
 * @Date 2024/3/29 21:53
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 地址的id
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) { // 没填写地址
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL); // 地址为空
        }
        // 购物车为空 也要抛出异常
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart); // 根据用户id去查询买的东西 看看是不是空的
        if(list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL); // 购物车数据为空
        }
        //正常下单

        //订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders); // 属性拷贝
        orders.setOrderTime(LocalDateTime.now()); // 下单时间
        orders.setPayStatus(Orders.UN_PAID); // 未付钱
        orders.setStatus(Orders.PENDING_PAYMENT); // 订单的状态 待付款
        orders.setNumber(System.currentTimeMillis() + ""); // 订单号
        orders.setPhone(addressBook.getPhone()); // 拿到用户的手机号
        orders.setConsignee(addressBook.getConsignee()); // 收货人
        orders.setUserId(userId); // 这个是很重要的
        orders.setAddress(addressBook.getDetail());
        orderMapper.insert(orders); // 要返回主键值
        //订单明细表N条数据
        //购物车里面的商品插入到订单明细表中
        List<OrderDetail>orderDetailList = new ArrayList<>();

        for(ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail); // 对象拷贝
            orderDetail.setOrderId(orders.getId()); // 主键回显
            orderDetailList.add(orderDetail);
        }
        //批量插入 效率高
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车数据
        shoppingCartMapper.deleteById(userId);
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }


    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修
        Integer OrderPaidStatus = Orders.PAID; //支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  //订单状态，待接单
        //发现没有将支付时间 check_out属性赋值，所以在这里更新
        LocalDateTime check_out_time = LocalDateTime.now();
        String orderNumber = ordersPaymentDTO.getOrderNumber();
        Orders order = orderMapper.getByNumber(orderNumber);

        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, order.getId());
        //通过websocket向客户端 浏览器 推送消息
        Map map = new HashMap();
        map.put("type", 1); // 1: 来单提醒  2: 客户催单
        map.put("orderId", order.getId());
        map.put("content", "订单号: " + ordersPaymentDTO.getOrderNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json); // 推送信息
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过websocket向客户端 浏览器 推送消息
        Map map = new HashMap();
        map.put("type", 1); // 1: 来单提醒  2: 客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号: " + outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json); // 推送信息
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVo = orderMapper.orderDetail(id);
        List<OrderDetail>orderDetailList = orderDetailMapper.getOrderDetailByOrderId(id);
        orderVo.setOrderDetailList(orderDetailList);
        orderVo.setOrderDishes(orderVo.getRemark());
        return orderVo;
    }

    /**
     * 用户取消
     * @param id
     */
    @Override
    public void cancel(Long id) {
        Orders find = orderMapper.getByOrdersId(id);
        if(find == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(find.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(id);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        Page<OrderVO> list = orderMapper.getPage(ordersPageQueryDTO);
        Page<OrderVO>result = new Page<>();

        for(OrderVO orderVO : list) {
            Long id = orderVO.getId();
            List<OrderDetail> orderDetailByOrderId = orderDetailMapper.getOrderDetailByOrderId(id);
            OrderVO t = new OrderVO();
            BeanUtils.copyProperties(orderVO, t);
            t.setOrderDetailList(orderDetailByOrderId);
            result.add(t);
        }
        PageResult pageResult = new PageResult(result.getTotal(), result.getResult());
        return pageResult;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailByOrderId(id);

        for (OrderDetail t : orderDetails) {
            BeanUtils.copyProperties(t, shoppingCart);
            shoppingCart.setId(null);

            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getByOrdersId(id);

        //校验订单是否存在
        if(order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过websocket向客户端 浏览器 推送消息
        Map map = new HashMap();
        map.put("type", 2); // 1: 来单提醒  2: 客户催单
        map.put("orderId", order.getId());
        map.put("content", "订单号: " + order.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json); // 推送信息
    }
}
